import { Row, Col, message, Spin, Modal } from 'antd';
import { CodeObject, DataBase, FieldObject, TableObject } from '@/type/global';
import CodeEditor from '@/components/CodeEditor';
import TableConfig from '@/components/TableConfig';
import { generateCode } from '@/common/generateCode';
import { useState, useEffect } from 'react';
import CodeView from '@/components/CodeView';
import { getKeyName } from '@/api';

const CreateTable = () => {

    const [code, setCode] = useState<CodeObject>({
        ts: '',
        java: '',
        sql: {
            create: '',
            insert: '',
            index: ''
        },
        json: '',
        proTable: '',
        proForm: ''
    });

    const [loading, setLoading] = useState(false);

    async function handleMakeField(value: TableObject) {
        if (!value.tableName) {
            message.warning('请输入表名称');
            return;
        }

        if (!value.fieldList || !value.fieldList.length) {
            message.warning('至少输入一个字段名');
            return;
        }

        if (!value.fieldList.every(item => item.fieldName)) {
            message.warning('请输入字段名');
            return;
        }
        const arr = value.fieldList;
        const newArr: FieldObject[] = [];
        // primaryKey
        // autoIncrement
        // isNull
        arr.forEach((item) => {
            item.isNull = item.options ? item.options.includes('isNull') : false;
            item.autoIncrement = item.options ? item.options.includes('autoIncrement') : false;
            item.primaryKey = item.options ? item.options.includes('primaryKey') : false;
            item.index = item.options ? item.options.includes('index') : false;
            newArr.push(item);
        })
        value.fieldList = newArr;
        setLoading(true);
        setCode(await generateCode(value));
        setLoading(false);
    }


    return (
        <div style={{ paddingTop: '24px' }}>

            <Row>
                <Col span={12}>
                    <TableConfig submit={handleMakeField} />
                </Col>
                <Col span={1}></Col>
                <Col span={11}>
                    <Spin spinning={loading} tip="正在生成数据，请稍后..." size="small">
                        <CodeView code={code} />
                    </Spin>
                </Col>
            </Row>
        </div>
    )
}

export default CreateTable
